<?php

namespace statistics\view\renderers\editor;

use statistics\utils\PHPScriptExecutor;
use statistics\view\renderers\ElementRenderer;
use statistics\model\statistic\Statistic;
use \FormElements;
use statistics\view\renderers\SelectBoxRenderer;

require_once (substr ( __DIR__, 0, strpos ( __DIR__, 'statistics' ) + 10 ) . DIRECTORY_SEPARATOR . 'includes.php');
require_once(SERVER_PATH.'/adm_program/system/classes/form_elements.php');

class FormStatisticRenderer extends ElementRenderer{
	private $actualFunctions;
	private $actualFunctionsTotal;
	private $currentStatistic;
	private $allStatisticConfigurations;
	
	public function __construct(Statistic $currentStatistic,$allStatisticConfigurations) {
		parent::__construct ();
		$this->currentStatistic = $currentStatistic;
		$this->allStatisticConfigurations = $allStatisticConfigurations;
		$this->initFunctionArrays();
	}
	
	public function renderElement() {
		$this->renderForm ();
	}
	private function renderForm() {
		$this->renderedElementHTML .= '
		<div class="formHead">Statistik-Editor</div>
		<form id="form_sta_config" name="form_sta_config" action="editor_process.php" method="post">';
	
		$this->renderFormBlockStatistic ();

		// $this->renderedElementHTML .= '<a rel="colorboxHelp" href="help.php?help_id=428"><img class="iconHelpLink" src="'. THEME_PATH. '/icons/help.png" alt="Help" title="Hilfe zum Hinzufügen von Tabellen anzeigen" /></a>';
		$this->renderedElementHTML .= '<br /><input type="button" name="show_statistic" value="Statistik anzeigen" onclick="javascript: doFormSubmit(\'show\')" />';
		$this->renderedElementHTML .= '<a rel="colorboxHelp" href="help.php?help_id=427"><img class="iconHelpLink" src="' . THEME_PATH . '/icons/help.png" alt="Help" title="Hilfe zur Statistik-Vorschau anzeigen" /></a>';
	
		$this->renderedElementHTML .= '</form>';
	}
	private function renderFormBlockStatistic() {
		$this->renderedElementHTML .= '<div class= "stdDiv" id="div_config_selection">';
		$this->renderStatisticActionMenu();
		$this->renderGeneralStatisticConfigurations ();
		$this->renderTables();
		$this->renderedElementHTML .= '   </div>';
	}
	private function renderStatisticActionMenu() {
		$selectBox = new SelectBoxRenderer();
	
		$selectStatisticID = array_search ( $this->currentStatistic->getDbID(), array_keys ( $this->allStatisticConfigurations ) );
		if ($this->currentStatistic->getDbID() == 1) {
			$selectStatisticID = - 1;
		}
		$selectBox->setSelectedEntry ( $selectStatisticID );
		$selectBox->setHTMLAttributes ( 'onchange="loadConf()"' );
		$selectBox->setZeroValue ( 1 );
		$selectBox->setZeroText ( 'neue Statistik erstellen..' );
	
		$this->renderedElementHTML .= '
	    	<p>Möchtest du eine gespeicherte Konfiguration laden und verändern oder eine neue Statistikkonfiguration erstellen?</p>' . $selectBox->generateStatisticConfigSelectBox ( $this->allStatisticConfigurations, 'statistic_conf_select' ) . '
            <a href="javascript: doFormSubmit(\'save\')"><img
                        src="' . THEME_PATH . '/icons/disk.png" title="Konfiguration speichern" alt="Konfiguration speichern"/></a>
            <a href="javascript: doFormSubmit(\'saveas\')"><img
                        src="' . THEME_PATH . '/icons/disk_copy.png" title="Konfiguration speichern unter" alt="Konfiguration speichern unter"/></a>
            <a href="javascript: loadConf(true)"><img
                        src="' . THEME_PATH . '/icons/add.png" title="neue Konfiguration erstellen" alt="neue Konfiguration erstellen"/></a>
            <a href="javascript: loadConf()"><img
                        src="' . THEME_PATH . '/icons/arrow_turn_left.png" title="alle Änderungen an der aktuellen Konfiguration rückgängig machen" alt="rückgängig"/></a>
            <a href="javascript: deleteConfiguration()"><img
                        src="' . THEME_PATH . '/icons/delete.png" title="Konfiguration löschen" alt="Konfiguration löschen"/></a>
            <a href="../resources/Benutzerhandbuch.pdf"><img
                        src="' . THEME_PATH . '/icons/help.png" alt="Help" title="Handbuch des Statistik-Plugins öffnen" /></a>';
	}
	private function renderGeneralStatisticConfigurations() {
		$tables = $this->currentStatistic->getTables ();
		$nrOfTables = count ( $tables );
		$this->renderedElementHTML .= '
                <h3>Allgemeine Angaben zur Statistik</h3>
                <div class ="InputLabelBox">
                    <span class="textLabel">Titel der Statistik</span>
                    <input class ="textInput" type="text" name="statistic_title" id="statistic_title" value="' . $this->currentStatistic->getTitle () . '">
                </div>
                <div class ="InputLabelBox">
                    <span class="textLabel">Untertitel der Statistik</span>
                    <input class ="textInput" type="text" name="statistic_subtitle" id="statistic_subtitle" value="' . $this->currentStatistic->getSubtitle () . '">
                </div>
                <div class ="InputLabelBox">
                    <span class="textLabel">Standardrolle der Statistik</span>
                    <a rel="colorboxHelp" href="help.php?help_id=533">
                        <img class="iconHelpLink" src="' . THEME_PATH . '/icons/help.png" alt="Help" title="Hilfe zur Standardrolle anzeigen" />
                    </a>' . FormElements::generateRoleSelectBox ( $this->currentStatistic->getStandardRoleID (), 'statistic_std_role' ) . '
                    <input class ="textInput" type="hidden" name="nr_of_tables" id="nr_of_tables" value="' . $nrOfTables . '">
		    	</div>';
	}	
	private function generateClassSuffix($actualElement, $nrOfElements) {
		$classSuffix = "";
	
		if ($actualElement == 0) {
			$classSuffix = "_first";
		} elseif ($actualElement == 1) {
			$classSuffix = "_second";
		} elseif ($actualElement == $nrOfElements - 1) {
			$classSuffix = "_last";
		}
	
		return $classSuffix;
	}
	private function initFunctionArrays() {
		$this->actualFunctions = array (
				'#' => '#',
				'%' => '%',
				'min' => 'min',
				'max' => 'max',
				'avg' => 'avg',
				'sum' => 'sum' 
		);
		$this->actualFunctionsTotal = array (
				'' => 'keine',
				'min' => 'min',
				'max' => 'max',
				'avg' => 'avg',
				'sum' => 'sum' 
		);		
	}
	private function renderTables() {
		$tables = $this->currentStatistic->getTables ();
		$nrOfTables = count ( $tables );
		
		// Schleife für die Erzegung der Eingabemaske für die Tabellen-Konfigurationen
		for($tc = 0; $tc < $nrOfTables; $tc ++) {
			$columns = $tables [$tc]->getColumns ();
			$rows = $tables [$tc]->getRows ();
			
			$this->renderedElementHTML .= '
            <div class= "stdDiv" id="div_table' . $tc . '_config">
                <h3>' . ($tc + 1) . '. Tabelle</h3>
                <div class ="InputLabelBox">
                    <span class="textLabel">Titel der Tabelle</span>
                    <input class ="textInput" type="text" name="table' . $tc . '_title" id="table' . $tc . '_title" value="' . $tables [$tc]->getTitle () . '">
                </div>
                <div class ="InputLabelBox">
                    <span class="textLabel">Rolle der Tabelle</span>
                    <a rel="colorboxHelp" href="help.php?help_id=542">
                        <img class="iconHelpLink" src="' . THEME_PATH . '/icons/help.png" alt="Help" title="Hilfe zur Rolle der Tabelle anzeigen" />
                    </a>' . FormElements::generateRoleSelectBox ( $tables [$tc]->getRoleID (), 'table' . $tc . '_role" class="roleInput' ) . '
                </div>';
			
			$this->renderColumns($columns, $tc);
			
			$this->renderRows($tables, $rows, $tc);
				
			if ($tc == $nrOfTables - 1) {
				$this->renderedElementHTML .= '<a href="javascript: editStructure(\'addtable\')" title="Tabelle hinzufügen"><img class="iconLink" src="' . THEME_PATH . '/icons/add.png" alt="Tabelle hinzufügen"/></a>';
			}
			if ($tc > 0) {
				$this->renderedElementHTML .= '<a href="javascript: editStructure(\'mvtable\',\'' . $tc . '\',\'\',\'\',\'true\')" title="Tabelle nach oben verschieben"><img class="iconLink" src="' . THEME_PATH . '/icons/arrow_up.png" alt="Tabelle nach oben verschieben"/></a>';
			}
			if ($tc < $nrOfTables - 1) {
				$this->renderedElementHTML .= '<a href="javascript: editStructure(\'mvtable\',\'' . $tc . '\')" title="Tabelle nach unten verschieben"><img class="iconLink" src="' . THEME_PATH . '/icons/arrow_down.png" alt="Tabelle nach unten verschieben"/></a>';
			}
			$this->renderedElementHTML .= '<a href="javascript: editStructure(\'dupltable\',\'' . $tc . '\')" title="Tabelle duplizieren"><img class="iconLink" src="' . THEME_PATH . '/icons/application_double.png" alt="Tabelle duplizieren"/></a>';
			if ($nrOfTables > 1) {
				$this->renderedElementHTML .= '<a href="javascript: editStructure(\'deltable\',\'' . $tc . '\')" title="Tabelle löschen"><img class="iconLink, helpRight" src="' . THEME_PATH . '/icons/delete.png" alt="Tabelle löschen"/></a>';
			}
				
			$this->renderedElementHTML .= '</div>';
		}
		
	}
	private function renderRows($tables, $rows, $tc) {
		$selectBox = new SelectBoxRenderer();
		$effectiveNrOfRows = count ( $rows );		
		$nrOfRows = $effectiveNrOfRows + 3;
		
		$formRowLabels = array (
				"Zeilen",
				"Bezeichnung",
				"Auswahl",
				"Bedingung",
				""
		);
		$formRowInputNames = array (
				"first",
				"label",
				"profile_field",
				"condition",
				"last"
		);
		
		$this->renderedElementHTML .= '
            <div class= "stdDiv" id="div_table' . $tc . '_row_config">
                <table class="row_conf_tbl">';
		
		for($rc = 0; $rc < $nrOfRows; $rc ++) {
			$rowIdf = $rc - 2;
			$classSuffix = $this->generateClassSuffix ( $rc, $nrOfRows );
			if ($rc == 0) {
				$this->renderedElementHTML .= '<thead>';
			} elseif ($rc == 1) {
				$this->renderedElementHTML .= '<tbody>';
			}
			$this->renderedElementHTML .= '<tr class="row_conf_tbl_row' . $classSuffix . '">';
			for($frmCol = 0; $frmCol < 5; $frmCol ++) {
				$this->renderedElementHTML .= '<td class="row_conf_tbl_col_' . $formRowInputNames [$frmCol] . $classSuffix . '">';
				if ($rc == 0) {
					$this->renderedElementHTML .= $formRowLabels [$frmCol];
					if ($frmCol > 0 && $frmCol < 4) {
						$this->renderedElementHTML .= '
                            <a rel="colorboxHelp" href="help.php?help_id=56' . ($frmCol + 1) . '">
                                <img class="iconHelpLink" src="' . THEME_PATH . '/icons/help.png" alt="Help" title="Hilfe zu diesem Thema anzeigen" />
                            </a>';
					}
				} elseif ($rc == 1) {
					if ($frmCol == 0) {
						$this->renderedElementHTML .= 'Kopfzeile';
					} elseif ($frmCol == 1) {
						$this->renderedElementHTML .= '<input name="table' . $tc . '_first_column_label" id="table' . $tc . '_first_column_label" type="text" value="' . $tables [$tc]->getFirstColumnLabel () . '">';
					}
				} elseif ($rc == $nrOfRows - 1) {
				} else {
					if ($frmCol == 0) {
						$this->renderedElementHTML .= ($rc - 1) . '. Zeile';
						$this->renderedElementHTML .= '<a href="javascript: editStructure(\'duplrow\',\'' . $tc . '\',\'\',\'' . $rowIdf . '\')" title="Zeile duplizieren"><img class="iconLink, helpRight" src="' . THEME_PATH . '/icons/application_double.png" alt="Zeile duplizieren"/></a>';
						if ($rc < $nrOfRows - 2) {
							$this->renderedElementHTML .= '<a href="javascript: editStructure(\'mvrow\',\'' . $tc . '\',\'\',\'' . $rowIdf . '\')" title="Zeile nach unten verschieben"><img class="iconLink, helpRight" src="' . THEME_PATH . '/icons/arrow_down.png" alt="Zeile nach unten"/></a>';
						}
						if ($rc > 2) {
							$this->renderedElementHTML .= '<a href="javascript: editStructure(\'mvrow\',\'' . $tc . '\',\'\',\'' . $rowIdf . '\',\'true\')" title="Zeile nach oben verschieben"><img class="iconLink, helpRight" src="' . THEME_PATH . '/icons/arrow_up.png" alt="Zeile nach oben"/></a>';
						}
						if ($rc == $nrOfRows - 2) {
							$this->renderedElementHTML .= '<a href="javascript: editStructure(\'addrow\',\'' . $tc . '\')" title="Zeile hinzufügen"><img class="iconLink, helpRight" src="' . THEME_PATH . '/icons/add.png" alt="Zeile hinzufügen" /></a>';
						}
					} elseif ($frmCol == 1) {
						$this->renderedElementHTML .= '<input name="table' . $tc . '_row' . $rowIdf . '_' . $formRowInputNames [$frmCol] . '" id="table' . $tc . '_row' . $rowIdf . '_' . $formRowInputNames [$frmCol] . '" type="text" value="' . $rows [$rowIdf]->getLabel () . '">';
					} elseif ($frmCol == 2) {
						$selectBox->setZeroValue ( '0' );
						$selectBox->setZeroText ( 'Alle' );
						$selectBox->setSelectedEntry ( $rows [$rowIdf]->getCondition ()->getProfileFieldID () );
						$selectBox->setHTMLAttributes ( 'onchange="disableConditionInput(this)"' );
						$this->renderedElementHTML .= $selectBox->generateProfileFieldSelectBox ( 'table' . $tc . '_row' . $rowIdf . '_' . $formRowInputNames [$frmCol] );
					} elseif ($frmCol == 3) {
						$this->renderedElementHTML .= '<input name="table' . $tc . '_row' . $rowIdf . '_' . $formRowInputNames [$frmCol] . '" id="table' . $tc . '_row' . $rowIdf . '_' . $formRowInputNames [$frmCol] . '" type="text" value="' . $rows [$rowIdf]->getCondition ()->getUserCondition () . '">';
					} elseif ($frmCol == 4) {
						if ($effectiveNrOfRows > 1) {
							$this->renderedElementHTML .= '<a href="javascript: editStructure(\'delrow\',\'' . $tc . '\',\'\',\'' . $rowIdf . '\')" title="Zeile löschen"><img class="iconLink" src="' . THEME_PATH . '/icons/delete.png" alt="Zeile löschen"/></a>';
						}
					}
				}
				$this->renderedElementHTML .= '</td>';
			}
			$this->renderedElementHTML .= '</tr>';
			
			if ($rc == 0) {
				$this->renderedElementHTML .= '</thead>';
			} elseif ($rc == $nrOfRows - 1) {
				$this->renderedElementHTML .= '</tbody>';
			}
		}
		$this->renderedElementHTML .= ' <input type="hidden" name="table' . $tc . '_nr_of_rows" id="table' . $tc . '_nr_of_rows" value="' . $effectiveNrOfRows . '">';
		
		$this->renderedElementHTML .= '</table>';
		// $this->renderedElementHTML .= '<span class="iconTextLink"><a href="javascript: editStructure(\'addrow\',\''.$tc.'\')" title="Zeile hinzufügen"><img class="iconLink" src="'. THEME_PATH. '/icons/add.png" alt="Zeile hinzufügen" /></a>';
		// $this->renderedElementHTML .= '&nbsp;<a href="javascript: editStructure(\'addrow\')"></a></span>';
		$this->renderedElementHTML .= '</div>';
	}
	private function renderColumns($columns, $tc) {	
		$effectiveNrOfColumns = count ( $columns );
		$nrOfColumns = $effectiveNrOfColumns + 1;
		
		$selectBox = new SelectBoxRenderer();
		
		$formColumnLabels = array (
				'Spalten',
				'Bezeichnung',
				'Auswahl',
				'Bedingung',
				'Auswerten',
				'Funktion',
				'Total-Funktion',
				''
		);
		$formColumnInputNames = array (
				'first',
				'label',
				'profile_field',
				'condition',
				'func_arg',
				'func_main',
				'func_total',
				'last'
		);
		$formColumnInputSelectValues = array (
				'func_main' => $this->actualFunctions,
				'func_total' => $this->actualFunctionsTotal
		);	
		$this->renderedElementHTML .= '
		<div class= "stdDiv" id="div_table' . $tc . '_column_config">
			<table class="col_conf_tbl">';
		
		for($frmRow = 0; $frmRow < 8; $frmRow ++) {
			if ($frmRow == 0) {
				$this->renderedElementHTML .= '<thead>';
			} elseif ($frmRow == 1) {
				$this->renderedElementHTML .= '<tbody>';
			}			
			$this->renderedElementHTML .= '<tr class="col_conf_tbl_row_' . $formColumnInputNames [$frmRow] . '">';
			for($cc = 0; $cc < $nrOfColumns; $cc ++) {			
				$classSuffix = $this->generateClassSuffix ( $cc, $nrOfColumns );
				$this->renderedElementHTML .= '<td class="col_conf_tbl_col_' . $formColumnInputNames [$frmRow] . $classSuffix . '">';
				if ($cc == 0) {
					if ($frmRow == 7) {
					} else {
						$this->renderedElementHTML .= $formColumnLabels [$frmRow];
					}				
					if ($frmRow > 0 && $frmRow < 7) {
						$this->renderedElementHTML .= '
                            <a rel="colorboxHelp" href="help.php?help_id=55' . $frmRow . '">
                                <img class="iconHelpLink helpRight" src="' . THEME_PATH . '/icons/help.png" alt="Help" title="Hilfe zu diesem Thema anzeigen" />
                            </a>';
					}
				} else {
					$colIdf = $cc - 1;
					if ($frmRow == 0) {
						$this->renderedElementHTML .= ($cc) . '. Spalte';
					} elseif ($frmRow == 1) {
						$this->renderedElementHTML .= '<input name="table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow] . '" id="table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow] . '" type="text" value="' . $columns [$colIdf]->getLabel () . '">';
					} elseif ($frmRow == 2) {
						$selectBox->setZeroValue ( '0' );
						$selectBox->setZeroText ( 'Alle' );
						$selectBox->setSelectedEntry ( $columns [$colIdf]->getCondition ()->getProfileFieldID () );
						$selectBox->setShowGrouping ( true );
						$selectBox->setShowMasterData ( false );
						$selectBox->setShowRoleInformation ( false );
						$selectBox->setHTMLAttributes ( 'onchange=" disableConditionInput(this)"' );
						$this->renderedElementHTML .= $selectBox->generateProfileFieldSelectBox ( 'table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow] );
					} elseif ($frmRow == 3) {
						$this->renderedElementHTML .= '<input name="table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow] . '" id="table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow] . '" type="text" value="' . $columns [$colIdf]->getCondition ()->getUserCondition () . '">';
					} elseif ($frmRow == 4) {
						$selectBox->setZeroValue ( '0' );
						$selectBox->setZeroText ( 'Auswahl' );
						$selectBox->setSelectedEntry ( $columns [$colIdf]->getFunction ()->getArgument () );
						$selectBox->setHTMLAttributes ( 'onchange="disableInvalidFunctions(this)"' );
						$this->renderedElementHTML .= $selectBox->generateProfileFieldSelectBox ( 'table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow] );
					} elseif ($frmRow == 5) {
						$this->renderedElementHTML .= FormElements::generateDynamicSelectBox ( $formColumnInputSelectValues [$formColumnInputNames [$frmRow]], $columns [$colIdf]->getFunction ()->getName (), 'table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow], false );
					} elseif ($frmRow == 6) {
						$this->renderedElementHTML .= FormElements::generateDynamicSelectBox ( $formColumnInputSelectValues [$formColumnInputNames [$frmRow]], $columns [$colIdf]->getFunctionTotal (), 'table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow], false );
					} elseif ($frmRow == 7) {
						
						if ($cc > 1) {
							$this->renderedElementHTML .= '<a href="javascript: editStructure(\'mvcol\',\'' . $tc . '\',\'' . $colIdf . '\',\'\',\'true\')" title="Spalte nach vorne verschieben"><img class="iconLink" src="' . THEME_PATH . '/icons/back.png" alt="Spalte nach vorne verschieben"/></a>';
						}
						if ($cc < $effectiveNrOfColumns) {
							$this->renderedElementHTML .= '<a href="javascript: editStructure(\'mvcol\',\'' . $tc . '\',\'' . $colIdf . '\')" title="Spalte nach hinten verschieben"><img class="iconLink" src="' . THEME_PATH . '/icons/forward.png" alt="Spalte nach hinten verschieben"/></a>';
						}
						$this->renderedElementHTML .= '<a href="javascript: editStructure(\'duplcol\',\'' . $tc . '\',\'' . $colIdf . '\')" title="Spalte duplizieren"><img class="iconLink" src="' . THEME_PATH . '/icons/application_double.png" alt="Spalte duplizieren"/></a>';
						if ($effectiveNrOfColumns > 1) {
							$this->renderedElementHTML .= '<a href="javascript: editStructure(\'delcol\',\'' . $tc . '\',\'' . $colIdf . '\')" title="Spalte löschen"><img class="iconLink" src="' . THEME_PATH . '/icons/delete.png" alt="Spalte löschen"/></a>';
						}
						if ($cc == $effectiveNrOfColumns) {
							$this->renderedElementHTML .= '<a href="javascript: editStructure(\'addcol\',\'' . $tc . '\')" title="Spalte hinzufügen"><img class="iconLink, helpRight" src="' . THEME_PATH . '/icons/add.png" alt="Spalte hinzufügen"/></a>';
						}
					} else {
						$this->renderedElementHTML .= '<input name="table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow] . '" id="table' . $tc . '_column' . $colIdf . '_' . $formColumnInputNames [$frmRow] . '" type="text">';
					}
				}
				$this->renderedElementHTML .= '</td>';
			}
			$this->renderedElementHTML .= '</tr>';
			
			if ($frmRow == 0) {
				$this->renderedElementHTML .= '</thead>';
			} elseif ($frmRow == 7) {
				$this->renderedElementHTML .= '</tbody>';
			}
		}	
		$this->renderedElementHTML .= '<input type="hidden" name="table' . $tc . '_nr_of_columns" id="table' . $tc . '_nr_of_columns" value="' . $effectiveNrOfColumns . '">';
		$this->renderedElementHTML .= '
			</table>
		</div>';
	}
	
	public function getPageHeader(){
		return '<link rel="stylesheet" type="text/css" href="'.STATISTICS_WEB_ROOT.'/view/stylesheets/editor-stylesheet.css">
            <script src="'.STATISTICS_WEB_ROOT.'/view/scripts/editor-scripts.js" type="text/javascript"></script>';
	}
}

?>